import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:url_launcher/url_launcher.dart';

/// 富文本显示组件
/// 支持HTML格式的富文本内容显示
class RichTextViewer extends StatelessWidget {
  final String htmlContent;
  final TextStyle? defaultTextStyle;
  final EdgeInsets? padding;
  final bool shrinkWrap;
  final int? maxLines;
  final TextOverflow? overflow;

  const RichTextViewer({
    Key? key,
    required this.htmlContent,
    this.defaultTextStyle,
    this.padding,
    this.shrinkWrap = true,
    this.maxLines,
    this.overflow,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 如果内容为空或只是纯文本，直接显示
    if (htmlContent.isEmpty) {
      return const SizedBox.shrink();
    }

    // 检查是否包含HTML标签
    final bool isHtml = htmlContent.contains('<') && htmlContent.contains('>');

    if (!isHtml) {
      // 纯文本显示
      return Padding(
        padding: padding ?? EdgeInsets.zero,
        child: Text(
          htmlContent,
          style: defaultTextStyle ?? const TextStyle(fontSize: 14),
          maxLines: maxLines,
          overflow: overflow ?? TextOverflow.ellipsis,
        ),
      );
    }

    // 预处理HTML，移除空的img标签
    String processedHtml = _preprocessHtml(htmlContent);

    // HTML富文本显示
    return Html(
      data: processedHtml,
      shrinkWrap: shrinkWrap,
      style: {
        "body": Style(
          margin: Margins.zero,
          padding: HtmlPaddings.zero,
          fontSize: FontSize(defaultTextStyle?.fontSize ?? 14),
          color: defaultTextStyle?.color ?? Colors.black87,
          fontFamily: defaultTextStyle?.fontFamily,
        ),
        "p": Style(
          margin: Margins.only(bottom: 8),
          padding: HtmlPaddings.zero,
        ),
        "h1": Style(
          fontSize: FontSize(20),
          fontWeight: FontWeight.bold,
          margin: Margins.only(bottom: 12, top: 8),
        ),
        "h2": Style(
          fontSize: FontSize(18),
          fontWeight: FontWeight.bold,
          margin: Margins.only(bottom: 10, top: 6),
        ),
        "h3": Style(
          fontSize: FontSize(16),
          fontWeight: FontWeight.bold,
          margin: Margins.only(bottom: 8, top: 4),
        ),
        "strong": Style(
          fontWeight: FontWeight.bold,
        ),
        "em": Style(
          fontStyle: FontStyle.italic,
        ),
        "ul": Style(
          margin: Margins.only(left: 16, bottom: 8),
        ),
        "ol": Style(
          margin: Margins.only(left: 16, bottom: 8),
        ),
        "li": Style(
          margin: Margins.only(bottom: 4),
        ),
        "blockquote": Style(
          border: const Border(left: BorderSide(color: Colors.grey, width: 4)),
          margin: Margins.only(left: 16, bottom: 8),
          padding: HtmlPaddings.only(left: 12),
          backgroundColor: Colors.grey[50],
        ),
        "code": Style(
          backgroundColor: Colors.grey[100],
          padding: HtmlPaddings.all(4),
          fontFamily: 'monospace',
          fontSize: FontSize(13),
        ),
        "pre": Style(
          backgroundColor: Colors.grey[100],
          padding: HtmlPaddings.all(12),
          margin: Margins.only(bottom: 8),
          fontFamily: 'monospace',
          fontSize: FontSize(13),
        ),
        "a": Style(
          color: Colors.blue,
          textDecoration: TextDecoration.underline,
        ),
        "img": Style(
          margin: Margins.only(bottom: 8),
        ),
      },
      onLinkTap: (url, attributes, element) {
        if (url != null) {
          _launchUrl(url);
        }
      },
    );
  }

  /// 预处理HTML，移除空的或无效的img标签
  String _preprocessHtml(String html) {
    if (html.isEmpty) return html;

    String processed = html;

    // 1. 移除空src的img标签 <img src="" /> 或 <img src='' /> 或 <img src=" " />
    processed = processed.replaceAll(
        RegExp(r'''<img[^>]*src\s*=\s*["'][\s]*["'][^>]*/?>''',
            caseSensitive: false, dotAll: true),
        '');

    // 2. 移除没有src属性的img标签
    processed = processed.replaceAll(
        RegExp(r'<img(?![^>]*\bsrc\s*=)[^>]*>',
            caseSensitive: false, dotAll: true),
        '');

    // 3. 移除src不以http或https开头的img标签 (防止 file:/// 或其他协议导致的崩溃)
    processed = processed.replaceAll(
        RegExp(r'''<img[^>]*src\s*=\s*["'](?!https?://)[^"']*["'][^>]*/?>''',
            caseSensitive: false, dotAll: true),
        '');

    // 4. 移除包含 file:// 的img标签
    processed = processed.replaceAll(
        RegExp(r'''<img[^>]*src\s*=\s*["'][^"']*file://[^"']*["'][^>]*/?>''',
            caseSensitive: false, dotAll: true),
        '');

    // 5. 移除所有剩余的无效img标签（兜底处理）
    // 匹配所有img标签，然后检查src是否有效
    processed = processed.replaceAllMapped(
      RegExp(r'<img[^>]*>', caseSensitive: false, dotAll: true),
      (match) {
        final imgTag = match.group(0)!;
        // 提取src属性值
        final srcMatch =
            RegExp(r'''src\s*=\s*["']([^"']+)["']''', caseSensitive: false)
                .firstMatch(imgTag);
        if (srcMatch != null) {
          final src = srcMatch.group(1)?.trim() ?? '';
          // 如果src为空或不是http/https开头，移除这个img标签
          if (src.isEmpty || !src.startsWith(RegExp(r'https?://'))) {
            return '';
          }
        } else {
          // 没有src属性，移除
          return '';
        }
        return imgTag;
      },
    );

    return processed;
  }

  /// 启动URL
  void _launchUrl(String url) async {
    try {
      final uri = Uri.parse(url);
      if (await canLaunchUrl(uri)) {
        await launchUrl(uri, mode: LaunchMode.externalApplication);
      }
    } catch (e) {
      debugPrint('无法打开链接: $url, 错误: $e');
    }
  }

  /// 显示图片对话框
  void _showImageDialog(BuildContext context, String imageUrl) {
    // 简单的URL检查
    if (imageUrl.isEmpty || !imageUrl.startsWith(RegExp(r'https?://'))) {
      return;
    }

    showDialog(
      context: context,
      builder: (context) => Dialog(
        backgroundColor: Colors.transparent,
        child: Stack(
          children: [
            Center(
              child: InteractiveViewer(
                child: Image.network(
                  imageUrl,
                  fit: BoxFit.contain,
                  errorBuilder: (context, error, stackTrace) {
                    return Container(
                      padding: const EdgeInsets.all(20),
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: const Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(Icons.broken_image,
                              size: 50, color: Colors.grey),
                          SizedBox(height: 8),
                          Text('图片加载失败', style: TextStyle(color: Colors.grey)),
                        ],
                      ),
                    );
                  },
                ),
              ),
            ),
            Positioned(
              top: 40,
              right: 20,
              child: GestureDetector(
                onTap: () => Navigator.of(context).pop(),
                child: Container(
                  padding: const EdgeInsets.all(8),
                  decoration: const BoxDecoration(
                    color: Colors.black54,
                    shape: BoxShape.circle,
                  ),
                  child: const Icon(
                    Icons.close,
                    color: Colors.white,
                    size: 24,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// 富文本预览组件（用于列表显示）
class RichTextPreview extends StatelessWidget {
  final String htmlContent;
  final int maxLines;
  final TextStyle? textStyle;

  const RichTextPreview({
    Key? key,
    required this.htmlContent,
    this.maxLines = 3,
    this.textStyle,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (htmlContent.isEmpty) {
      return const SizedBox.shrink();
    }

    // 移除HTML标签，只显示纯文本预览
    final plainText = _stripHtmlTags(htmlContent);

    return Text(
      plainText,
      style: textStyle ?? const TextStyle(fontSize: 14),
      maxLines: maxLines,
      overflow: TextOverflow.ellipsis,
    );
  }

  /// 移除HTML标签
  String _stripHtmlTags(String htmlString) {
    final RegExp exp = RegExp(r"<[^>]*>", multiLine: true, caseSensitive: true);
    return htmlString.replaceAll(exp, '').trim();
  }
}
